<template>
  <el-dialog v-model="dialogVisible" title="修改头像" width="500px">
    <el-upload
      class="avatar-uploader"
      action="/api/file/s3Upload"
      method="post"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :headers="{ 'Authorization': tokenStore.token.token }"
      name="file"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAvatar">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useTokenStore } from '@/stores/token.js'
import { updateAvatarService } from '@/api/user.js'

const tokenStore = useTokenStore()
const dialogVisible = ref(false)
const imageUrl = ref('')
const avatarUrl = ref('')

const handleAvatarSuccess = (response, uploadFile) => {
  if (response.code === 1) {
    imageUrl.value = URL.createObjectURL(uploadFile.raw)
    avatarUrl.value = response.data
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

const submitAvatar = async () => {
  if (!avatarUrl.value) {
    ElMessage.error('请先上传头像')
    return
  }
  const result = await updateAvatarService(avatarUrl.value)
  if (result.code === 1) {
    ElMessage.success('头像更新成功')
    tokenStore.token.qqAvatar = avatarUrl.value
    dialogVisible.value = false
  } else {
    ElMessage.error(result.msg || '头像更新失败')
  }
}

const open = () => {
  dialogVisible.value = true
  imageUrl.value = tokenStore.token.qqAvatar
  avatarUrl.value = ''
}

defineExpose({
  open
})
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>